package com.example.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.api.ApiResult;
import com.example.entity.emp.SysRole;
import com.example.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理接口
 */
@Api(tags = "角色管理接口")
@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
public class SysRoleController {

    private final SysRoleService roleService;

    @GetMapping("/list")
    @ApiOperation("获取角色列表")
    public ApiResult<List<SysRole>> list() {
        List<SysRole> roles = roleService.list();
        return ApiResult.success(roles);
    }

    @GetMapping("/page")
    @ApiOperation("分页查询角色")
    public ApiResult<Page<SysRole>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String roleName) {

        Page<SysRole> page = roleService.page(current, size, roleName);
        return ApiResult.success(page);
    }

    @PostMapping
    @ApiOperation("新增角色")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> add(@Validated @RequestBody SysRole role) {
        roleService.add(role);
        return ApiResult.success();
    }

    @PutMapping
    @ApiOperation("修改角色")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> update(@Validated @RequestBody SysRole role) {
        roleService.update(role);
        return ApiResult.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除角色")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> delete(@PathVariable Long id) {
        roleService.delete(id);
        return ApiResult.success();
    }

    @PostMapping("/{roleId}/permissions")
    @ApiOperation("分配角色权限")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> assignPermissions(
            @PathVariable Long roleId,
            @RequestBody List<Long> permissionIds) {
        
        roleService.assignPermissions(roleId, permissionIds);
        return ApiResult.success();
    }

    @GetMapping("/user/{userId}")
    @ApiOperation("获取用户角色ID列表")
    public ApiResult<List<Long>> getUserRoleIds(@PathVariable Long userId) {
        return ApiResult.success(roleService.getUserRoleIds(userId));
    }

    @PostMapping("/user/{userId}")
    @ApiOperation("分配用户角色")
    @SaCheckRole("ROLE_ADMIN")
    public ApiResult<Void> assignUserRoles(
            @PathVariable Long userId,
            @RequestBody List<Long> roleIds) {
        
        roleService.assignUserRoles(userId, roleIds);
        return ApiResult.success();
    }
} 